package app

import (
	"context"
	"fmt"

	"charging_pile/common/uniqueid"
	"charging_pile/devices/device"
	"charging_pile/user/internal/svc"
	"charging_pile/user/internal/types"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type StartChargeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStartChargeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StartChargeLogic {
	return &StartChargeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StartChargeLogic) StartCharge(req *types.StartChargeReq) (resp *types.StartChargeResp, err error) {
	var userId int64 = 1 //:= ctxdata.GetUidFromCtx(l.ctx)
	logx.Infof("StartCharge req userid:%d", userId)
	user, err := l.svcCtx.Models.User.FindOne(l.ctx, userId)
	if err != nil {
		return nil, errors.Wrapf(err, "userId:%d", userId)
	}

	in := device.StartChargeReq{
		Order:     uniqueid.GenSn("wx"),
		User:      fmt.Sprintf("%08d00000000000000000000", user.Id),
		Pile:      req.Pile,
		Plug:      int32(req.Plug),
		UserType:  7,
		OrgCode:   "enng",
		CtlMode:   3,
		CtlParam:  10000,
		ChargeMod: 1,
	}
	_, err = l.svcCtx.DeviceRpc.StartCharge(l.ctx, &in)
	if err != nil {
		return nil, err
	}

	return resp, err
}
